const redis = require("redis");

module.exports = function (redisConfig) {

    let globalClient = redis.createClient(redisConfig);
    let sub = redis.createClient(Object.assign({}, redisConfig, {detect_buffers: true, return_buffers: false}));
    let pub = redis.createClient(Object.assign({}, redisConfig, {detect_buffers: true, return_buffers: false}));

    return {
        globalClient: globalClient,
        sub: sub,
        pub: pub,
        getSocketAdapter: function () {
            return {
                pubClient: redis.createClient(Object.assign({}, redisConfig, {return_buffers: true})),
                subClient: redis.createClient(Object.assign({}, redisConfig, {return_buffers: true}))
            };
        },
        cache: function (key, ttl, callback, refresh) {
            return new Promise(function (resolve, reject) {
                if (refresh) {
                    return callback().then(function (response) {
                        globalClient.setex(key, ttl, JSON.stringify(response));
                        resolve(response);
                    }, reject);
                }
                globalClient.get(key, (err, reply) => {
                    if (err) {
                        console.log('Redis Error:', err);
                    } else {
                        if (reply) {
                            return resolve(JSON.parse(reply));
                        }
                    }
                    return callback().then(function (response) {
                        globalClient.setex(key, ttl, JSON.stringify(response));
                        resolve(response);
                    }, reject);
                });
            });
        }
    };
};